package net.nohaven.proj.javeau.fs.real;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import net.nohaven.proj.javeau.fs.exceptions.EntityAlreadyPresentException;
import net.nohaven.proj.javeau.fs.exceptions.EntityNotFoundException;
import net.nohaven.proj.javeau.fs.exceptions.GenericIOException;
import net.nohaven.proj.javeau.fs.model.FSFile;
import net.nohaven.proj.javeau.fs.model.FSFileWriter;

public class RFSFileWriter implements FSFileWriter {
	protected File file;
	private OutputStream stream;

	public RFSFileWriter(File file) throws EntityAlreadyPresentException,
			GenericIOException {
		if (file.exists())
			throw new EntityAlreadyPresentException(
					"Directory or file already present");
		try {
			file.createNewFile();
		} catch (IOException e) {
			throw new GenericIOException(e.getMessage(), e);
		}

		this.file = file;
	}

	public void abort() throws IOException {
		stream.close();
		file.delete();
	}

	public FSFile commit() throws IOException {
		try {
			stream.close();
			return new RFSFile(file);
		} catch (EntityNotFoundException e) {
			//Impossible
			return null;
		}
	}

	public OutputStream getOutputStream() {
		try {
			stream = new FileOutputStream(file);
			return stream;
		} catch (FileNotFoundException e) {
			//Impossible
			return null;
		}
	}

}
